//
//  SelectEmployeeVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/29.
//  Copyright © 2017年 remotevillage. All rights reserved.
//


import UIKit
import Moya


class SelectEmployeeVC: BaseVC {

  // 属性传值,用于转交工单
  var orderId: String!
  
  var didSuccess: VoidClosure?
  
  // 选中转交人的id
  fileprivate var selectStaffId: String = ""
  
  fileprivate var sortChatUsers: [[ChatUser]] = []
  fileprivate var titles: [String] = []
  
  fileprivate var searchView: SJSearchBar!
  fileprivate var tableView: UITableView!
  
  fileprivate var okButton: UIButton!
  
  fileprivate var canclePull: Cancellable?
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = GlobalConfig.BGWhiteColor
    title = "转交工单给"

    create()
    
    pullData()
    
    if let _ = tableView.indexPathForSelectedRow {
      okButton.isSelected = true
    }
    
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    GlobalConfig.baiduStatisticsPageViewStart("转交选择员工")
  }
  
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    GlobalConfig.baiduStatisticsPageViewEnd("转交选择员工")
  }
  
  deinit {
    
    // 没有请求完退出,取消请求
    if let cancle = canclePull {
      
      cancle.cancel()
      
    }
    
  }
  
}

// MARK: - action

extension SelectEmployeeVC {
  @objc fileprivate func cancleAction() {
    
    let _ = navigationController?.popViewController(animated: true)
    
  }
  
  @objc fileprivate func okAction() {
    
    SJApp.showHUD()
    let _ = WorkorderRequest.shared.handleOrder(type: "TRANSFER", workOrderId: orderId, staffId: selectStaffId, replyContent: "", images: "", success: {
      SJHint.show("转交成功")
      let _ = self.navigationController?.popViewController(animated: true)
      if let temp = self.didSuccess { temp() }
    }) {  }
    
  }
}

// MARK: - fileprivate

extension SelectEmployeeVC {
  
  fileprivate func pullData() {
    
    canclePull = UserRequest.shared.getUserAddressBook { (chatUsers) in
      
      let sortData = AddressBookHelper.sortUser(chatUsers: chatUsers)
      self.sortChatUsers = sortData.0
      self.titles = sortData.1
      self.tableView.reloadData()
      
      SJCache.chatUsers = chatUsers
      
    }
    
  }
  
  fileprivate func create() {

    addBackTitleItem(title: "取消")
    
    
    okButton = ObserveButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
    okButton.setTitle("确定", for: .normal)
    okButton.titleLabel?.font = GlobalConfig.system16Font
    okButton.addTarget(self, action: #selector(okAction), for: .touchUpInside)
    okButton.isSelected = false
    okButton.contentHorizontalAlignment = .right
    let okItem = UIBarButtonItem(customView: okButton)
    navigationItem.rightBarButtonItem = okItem
    

    searchView = SJSearchBar()
    searchView.placeholder = "搜索"
    searchView.isCancleButton = false
    searchView.delegate = self
    view.addSubview(searchView)
    
    
    tableView = UITableView()
    tableView.backgroundColor = UIColor.clear
    tableView.frame = CGRect(x: 0, y: 44, width: UIScreen.width, height: UIScreen.noNavBarHeight - 108)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .none
    tableView.sectionIndexColor = GlobalConfig.BGSkyBlueColor
    tableView.sectionIndexBackgroundColor = UIColor.clear
    tableView.rowHeight = SelectEmployeeCell.height
    tableView.sectionHeaderHeight = 37
    let footer = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
    footer.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.tableFooterView = footer
    tableView.register(SelectEmployeeCell.self, forCellReuseIdentifier: SelectEmployeeCell.identifier)
    view.addSubview(tableView)
    
  }
}

// MARK: - 

extension SelectEmployeeVC: SJSearchBarDelegate {
  
  func didEndSearch() {
    
  }
  
  func didBeaginSearch() {
    
  }
  
  func didChange(text: String) {
    
    let users = SJCache.chatUsers
    
    if text.isEmpty {
      
      selectStaffId = ""
      okButton.isSelected = true
      let sortData = AddressBookHelper.sortUser(chatUsers: users)
      self.sortChatUsers = sortData.0
      self.titles = sortData.1
      self.tableView.reloadData()
      
      return
      
    }
    
    
    let filterUsers = users.filter { (user) -> Bool in
      
      if user.nickname.contains(text) {
        return true
      }
      else if user.phoneNumber.contains(text) {
        return true
      }
      return false
      
    }
    
    let sortData = AddressBookHelper.sortUser(chatUsers: filterUsers)
    self.sortChatUsers = sortData.0
    self.titles = sortData.1
    self.tableView.reloadData()
    
  }
  
}

// MARK: - UITableViewDataSource

extension SelectEmployeeVC : UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int { return titles.count }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sortChatUsers[section].count
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: SelectEmployeeCell.identifier) as! SelectEmployeeCell
    
    cell.model = sortChatUsers[indexPath.section][indexPath.row]
    
    return cell
  }
}

// MARK: - UITableViewDelegate

extension SelectEmployeeVC : UITableViewDelegate {
  
  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = SectionV(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 37))
    view.title = titles[section]
    return view
  }
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if sortChatUsers[indexPath.section][indexPath.row].id == User.staffId {
      selectStaffId = ""
      okButton.isSelected = false
      SJHint.show("不能转交给自己")
      return
    }
    
    selectStaffId = sortChatUsers[indexPath.section][indexPath.row].id
    okButton.isSelected = true
  }
  
  func sectionIndexTitles(for tableView: UITableView) -> [String]? { return titles }

}
